<?php 
/*
 module:		首页
 create_time:	2021-09-18 22:56:53
 author:		
 contact:		
*/

namespace app\api\controller;

use app\api\service\IndexService;
use app\api\model\Index as IndexModel;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use utils\weixinpay\wechatpay;

class Index extends Common {
    public $uid = '0';
    public function __construct(App $app)
    {
        parent::__construct($app);

        $action = ['index','personal','share'];

        $act = $this->request->action();

        if(in_array($act,$action)){
            $heade = $this->request->header('Authorization');
            if(!empty($heade)){
                $this->uid = $this->getUidByToken($this->request);
            }
        }else{
            $this->uid = $this->getUidByToken($this->request);
        }
    }

    public function index()
    {

        $data = [];
        $data['marvellous'][] = ['title'=>'ISTJ','value'=>'20'];
        $data['marvellous'][] = ['title'=>'ISTJ','value'=>'30'];
        $data['marvellous'][] = ['title'=>'ISTJ','value'=>'40'];
        $data['marvellous'][] = ['title'=>'ISTJ','value'=>'60'];
        $data['marvellous'][] = ['title'=>'ISTJ','value'=>'100'];
        $data['consu_state'] = 0;
        if(empty($this->uid)){
            $data['type'] =0;
        }else{
            $user = Db::name('users')->where('u_id',$this->uid)->find();
            if(empty($user)){
                $data['type'] =0;
                $this->ajaxSuccess($data);
            }
            $openid = $user['openid'];
            $order = Db::name('order')->where('openid',$openid)->where('state',1)->order('order_id desc')->find();
            if(empty($order)){

                $data['type'] =1;
            }else{
                $outcome = $order['outcome'];
                $data['outcome'] = $outcome;
                $data['out_state'] = $order['state'];
                $consult = Db::name('customer_list')
                    ->where('uid',$this->uid)
                    ->where('state',1)
                    ->field('tel,price,create_time,state,minute,type')
                    ->select()
                    ->toArray();
                if(!empty($consult)) {
                    foreach ($consult as $k=>$v){
                        $consult[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

                    }
                    $data['consu_state'] = 1;
                    $data['consu_data'] =$consult;
                }
                $data['type'] =2;
                $data['count'] = $user['count'];
                //分享的
                $shar = Db::name('order')
                    ->alias('o')
                    ->join('mbti m','o.mbti_id = m.mbti_id','left')
                    ->where('o.user_id',$this->uid)
                    ->where('o.state',1)
                    ->field('m.title,m.edition,m.describes,o.create_time')
                    ->select()
                    ->toArray();
                $s_arr = [];
                $time = time();
                foreach ($shar as $k=>$v){
                    $ts = ($time - $v['create_time']) / 86400;
                    $fs = (int)$ts;
                    if($fs== 0){
                        $jgs = '今天';
                    }else{
                        $jgs = $fs.'天前';
                    }
                    $s_arr[$k]['title'] =$jgs.'('.$v['title'].'-'.$v['edition'].')';
                    $s_arr[$k]['describe'] = $v['describes'];
                }
                $data['history'] = $s_arr;
            }
        }

        $this->ajaxSuccess($data);
    }

    //测试结果
    public function personal()
    {


        $user = Db::name('users')->where('u_id',$this->uid)->find();
        if(empty($user)){
            $data['type'] =0;
            $this->ajaxSuccess($data);
        }
        $openid = $user['openid'];

        $order = Db::name('order')
            ->where('openid',$openid)
            ->where('state',1)
            ->order('order_id desc')
            ->find();


        $data = [];
        if(empty($this->uid)){
            $data['type'] =0;
        }else if(empty($order)){
            $data['type'] =1;
        }else{
            if(empty($order['user_id'])){
                Db::name('order')->where('order_id',$order['order_id'])->update(['user_id'=>$this->uid]);
            }
            $data['order'] = $order['order_son'];
            $data['level'] = $order['level'];
            if($order['level'] == 1){
                $data['price'] = Db::name('mbti_prices')->where('mp_id',2)->value('complete_price');
            }
            $data['outcome'] = $order['outcome'];
            $data['type'] =2;
            $data['count'] = $user['count'];
            $list = [];
            $list[0]['title'] = '简单解读';
            $list[0]['content'] = '容忍、不拘泥；是冷静的观察者，但面临问题能迅速行动，找出可行的解决方法。能够分析哪些东西可以使事情进行顺利，找出实际问题的症结。很重视事情的前因后果，能够以理性的原则把事情组织起来，重视效率。';
            $list[1]['title'] = '基本解读';
            $list[1]['content'] = '容忍、不拘泥；是冷静的观察者，但面临问题能迅速行动，找出可行的解决方法。能够分析哪些东西可以使事情进行顺利，找出实际问题的症结。很重视事情的前因后果，能够以理性的原则把事情组织起来，重视效率。';
            $data['list'] = $list;
            $data['results'] = $this->results($order['outcome_json']);
            $data['sex'] = $user['gender'] == 2?'2':'1';
            $data['temperament'] = '匠心者，专家气质';
            $data['mold'] = '最擅长机械和实操相关技能的类型';
        }
        $this->ajaxSuccess($data);
    }

    public function results($json){
        $data = json_decode($json,true);
        $arr = ["T" => 0,
              "N" => 0,
              "E" => 0,
              "J" =>0,
              "F" =>0,
              "S" => 0,
              "I" =>0,
              "P" => 0];
        foreach ($data as $v){
            if(isset($arr[$v['choice']])){
                $arr[$v['choice']] += 1;
            }else{
                $arr[$v['choice']] = 1;
            }
        }

        $res = [];
        $ei = $arr['E'] + $arr['I'];
        if($arr['E'] == $arr['I']){
            $res[0]['di']= bcdiv($arr['I'],$ei,4) * 100;
            $res[0]['re']='I';
        }else if($arr['E'] < $arr['I']){
            $res[0]['di']=  bcdiv($arr['I'],$ei,4) * 100;
            $res[0]['re']= 'I';
        }else if($arr['E'] > $arr['I']){
            $res[0]['di']= bcdiv($arr['E'],$ei,4) * 100;
            $res[0]['re']= 'E';
        }

        $sn = $arr['S'] + $arr['N'];
        if($arr['S'] == $arr['N']){
            $res[1]['di']= bcdiv($arr['N'],$sn,4) * 100;
            $res[1]['re']= 'N';
        }else if($arr['S'] < $arr['N']){
            $res[1]['di']= bcdiv($arr['N'],$sn,4) * 100;
            $res[1]['re']= 'N';
        }else if($arr['S'] > $arr['N']){
            $res[1]['di']= bcdiv($arr['S'],$sn,4) * 100;
            $res[1]['re']= 'S';
        }
        $tf = $arr['T'] + $arr['F'];
        if($arr['T'] == $arr['F']){
            $res[2]['di']= bcdiv($arr['F'],$tf,4) * 100;
            $res[2]['re']= 'F';
        }else if($arr['T'] < $arr['F']){
            $res[2]['di']= bcdiv($arr['F'],$tf,4) * 100;
            $res[2]['re']= 'F';
        }else if($arr['T'] > $arr['F']){
            $res[2]['di']= bcdiv($arr['T'],$tf,4) * 100;
            $res[2]['re']= 'T';
        }
        $jp = $arr['J'] + $arr['P'];
        if($arr['J'] == $arr['P']){
            $res[3]['di']= bcdiv($arr['P'],$jp,4) * 100;
            $res[3]['re']= 'P';
        }else if($arr['J'] < $arr['P']){
            $res[3]['di']= bcdiv($arr['P'],$jp,4) * 100;
            $res[3]['re']= 'P';
        }else if($arr['J'] > $arr['P']){
            $res[3]['di']= bcdiv($arr['J'],$jp,4) * 100;
            $res[3]['re']= 'J';
        }
        return $res;
    }
    //测试题列表
    public function testTitle()
    {
        $list = Db::name('mbti')
            ->where('extension',1)
            ->order('mbti_id desc')
            ->select()->toArray();
        foreach ($list as $k=>$v){
            $list[$k]['img'] = 'http://'.$_SERVER['SERVER_NAME'].$v['img'];
        }
        return $this->ajaxSuccess($list);
    }
    //测试题题目
    public function testSubject()
    {
        $id = $this->request->param('id');
        if(!is_numeric($id)){
            return $this->ajaxError('没有找到资源');
        }
        $arr = Db::name('mbti')
            ->where('extension',1)
            ->order('mbti_id desc')
            ->limit(2)
            ->column('mbti_id');
        if(!in_array($id,$arr)){
            return $this->ajaxError('没有找到资源');
        }

        $mbti = Db::name('mbti')->where('mbti_id',$id)->find();
        $mbti_subject = Db::name('mbti_subject')
            ->where('mbti_id',$mbti['mbti_id'])
            ->select()->toArray();
        if(empty($mbti_subject)){
            return $this->ajaxError('没有找到资源');
        }
        $arr = [];
        $data = [1=>['title'=>'词对题','arr'=>[]],2=>['title'=>'描述题','arr'=>[]],3=>['title'=>'验证题','arr'=>[]],4=>['title'=>'终测题','arr'=>[]]];
        foreach ($mbti_subject as $v){
            $v['options'] = explode(',_',$v['options']);
            $v['fraction'] = explode(',_',$v['fraction']);
            $v['choice'] = '';
            $v['how'] = '';
            $arr[$v['type']][] = $v;
        }
        ksort($arr);
        $json = [];
        $data[1]['sum'] = count($arr[1]);
        $data[1]['count'] = 0;
        $data[2]['sum'] = count($arr[2]);
        $data[2]['count'] =0;
        $data[3]['sum'] = count($arr[3]);
        $data[3]['count'] = 0;
        $data[4]['sum'] = count($arr[4]);
        $data[4]['count'] = 0;
        $json = array_merge($arr[1],$arr[2],$arr[3],$arr[4]);

        $res = [];
        $res['mbti_id'] = $id;
        $res['data'] = $data;
        $res['json'] = $json;
        $res['count'] = count($data);
       return $this->ajaxSuccess($res);
    }

    public function  testSuccess()
    {
        $post = $this->request->post('data');
        $mbti_id = $this->request->post('id');
        $post = htmlspecialchars_decode($post);
        $post ='['.$post.']';
        $post = json_decode($post,true);
        $data = [];
        foreach ($post as $v){
            $data[$v['subject_id']]['choice'] = $v['choice'];
            $data[$v['subject_id']]['how'] = $v['how'];
        }
        $res = mbit_calculation($data);
        $json = json_encode($data);
        $mbti = Db::name('mbti')->where('mbti_id',$mbti_id)->find();
        $user = Db::name('users')->where('u_id',$this->uid)->find();
        $type = 0;
        $data = [];
        $openid = $user['openid'];
        $order = Db::name('order')->where('state',1)->where('openid',$openid)->count();
        if($order < 1 && !empty($user['pid'])){
            $data['pay_type'] = '4';
            $data['state'] = '1';
            $data['level'] = '1';
            $type = 1;
        }else if($user['count'] > 0){
            $data['pay_type'] = '3';
            $data['state'] = '1';
            $data['level'] = '2';
            $type = 1;
            Db::name('users')->where('u_id',$this->uid)->dec('count')->update();
        }else{
            $data['pay_type'] = '1';
            $data['state'] = '0';
        }
        $order =doOrderSn('DSS');
        $data['order_son'] = $order;
        $data['title'] = $mbti['title'];
        $data['price'] = $mbti['price'];
        $data['money'] = $mbti['money'];
        $data['create_time'] = time();
        $data['outcome_json'] = $json;
        $data['outcome'] = $res;
        $data['mbti_id'] = $mbti_id;
        $data['openid'] = $openid;
        $o = Db::name('order')->insert($data);
        $r = [];
        $r['order'] = $order;
        $r['type'] = $type;
        if($o){
            $this->ajaxSuccess($r);
        }else{
            $this->ajaxError('请稍后再试');
        }
    }

    public function share()
    {
        $data = [];
        if(empty($this->uid)){

            $data['type'] =0;
        }else{
            $user = Db::name('users')->where('u_id',$this->uid)->find();
            if(empty($user)){
                $data['type'] =0;
                $this->ajaxSuccess($data);
            }
            $list = Db::name('users')->where('pid',$this->uid)->select()->toArray();
            $data['type'] =1;
            foreach ($list as $k=>$v){
                $outcome = Db::name('order')->where('openid',$v['openid'])->order('order_id desc')->value('outcome');
                $list[$k]['outcome'] = $outcome.'，成功者';
            }
            $data['list'] = $list;
        }

        $this->ajaxSuccess($data);
    }

    //支付页
    public function outcome()
    {
        $order_no = $this->request->param('order_no');
        $order = Db::name('order')->where('order_son',$order_no)->find();
        if(empty($order)){
            $openid = Db::name('users')->where('u_id',$this->uid)->value('openid');
            $order = Db::name('order')
                ->where('openid',$openid)
                ->where('state',1)
                ->order('order_id desc')
                ->find();
            if(empty($order)){
                $this->ajaxError('未找到订单号');
            }
        }
        $pay = [];
        $data = [];
        $data['outcome'] = $order['outcome'];
        $data['level'] = $order['level'];
        if($order['level'] == 1){//基础班版
            //查找完整版价格
            $pay[0]['title'] = '完整解读';
            $pay[0]['describe'] = '结果+完整解读';
            $pay[0]['price'] = '9.9';
            $pay[0]['money'] = '29';
            $pay[1]['title'] = '小程序VIP';
            $pay[1]['describe'] = '完整解读+可重测3次';
            $pay[1]['price'] = '19.9';
            $pay[1]['money'] = '88';
        }else if($order['level'] == 2){

            $pay[0]['title'] = '小程序VIP';
            $pay[0]['describe'] = '完整解读+可重测3次';
            $pay[0]['price'] = '9.9';
            $pay[0]['money'] = '88';
        }else{
            $pay[0]['title'] = '完成解读';
            $pay[0]['describe'] = '结果+完整解读';
            $pay[0]['price'] = '19';
            $pay[0]['money'] = '29';
            $pay[1]['title'] = '小程序VIP';
            $pay[1]['describe'] = '完整解读+可重测3次';
            $pay[1]['price'] = '28';
            $pay[1]['money'] = '88';
        }

        $mbti = Db::name('mbti')->where('mbti_id',$order['mbti_id'])->find();
        $data['level'] = $order['level'];
        $data['pay'] = $pay;
        $data['time'] = date('Y-m-d H:i:s',$order['create_time']);
        $data['count_down'] = time() + 600;
        $this->ajaxSuccess($data);
    }

    //微信支付
    public function pay(){
        $order_no = $this->request->param('order_no');
        $state = $this->request->param('state');
        $order = Db::name('order')->where('order_son',$order_no)->find();
        $openid = Db::name('users')->where('u_id',$this->uid)->value('openid');
        if(empty($order)){
            $this->error('未找到订单号');
        }
        $o_son = doOrderSn('DSS');
        if($order['level'] == 1){//基础班版
            //查找完整版价格
            $pay[0]['title'] = '完整解读';
            $pay[0]['describe'] = '结果+完整解读';
            $pay[0]['price'] = '9.9';
            $pay[0]['money'] = '29';
            $pay[1]['title'] = '小程序VIP';
            $pay[1]['describe'] = '完整解读+可重测3次';
            $pay[1]['price'] = '19.9';
            $pay[1]['money'] = '88';
            $order_no = $o_son;
            if($state == 1){
                $price =  $pay[1]['price'];
            }else{
                $price =  $pay[0]['price'];
            }
//
        }else if($order['level'] == 2){
            $pay[0]['title'] = '小程序VIP';
            $pay[0]['describe'] = '完整解读+可重测3次';
            $pay[0]['price'] = '9.9';
            $pay[0]['money'] = '88';
            $order_no = $o_son;
            $state = 1;
            $price =  $pay[0]['price'];
            //增加次数
//
        }else{
            $pay[0]['title'] = '完成解读';
            $pay[0]['describe'] = '结果+完整解读';
            $pay[0]['price'] = '19';
            $pay[0]['money'] = '29';
            $pay[1]['title'] = '小程序VIP';
            $pay[1]['describe'] = '完整解读+可重测3次';
            $pay[1]['price'] = '28';
            $pay[1]['money'] = '88';
            if($state == 1){
                $zj_price = $pay[1]['price'];
            }else{
                $zj_price =  $pay[0]['price'];
            }
            Db::name('order')->where('order_son',$order_no)->update(['actual_price'=>$zj_price]);

        }
        //增加记录
        Db::name('order_record')->insert([
            'o_id'=>$order['order_id'],
            'sc_order'=>$order_no,
            'level'=>$order['level'],
            'state'=>0,
            'price'=>$price,
            'type'=>$state,
            'uid'=>$this->uid
        ]);


        $wxpay = new wechatpay(1);
        $order = array(
            'body'         => 'mbit购买',
            'detail'       => 'mbit购买',
            'total_fee'    => '0.01' * 100, //分
            'out_trade_no' => $order_no,
            'trade_type'=>'JSAPI',
            'notify_url'       => 'https://xlcp.redyin.net/home/index/xcx_notify',
        );
        $res = $wxpay ->jspay($order,$openid);
        $data = json_decode($res);
        $this->ajaxSuccess($data);
    }
    //预约
    public function customer()
    {

        $price = Db::name('customer_money')->where('state',1)->order('sort asc')->limit(3)->select()->toArray();

        $data = [];
        $data['price'] = $price;
        //评价
        $evaluate = [];
        $evaluate[0]['name'] = '超级大可爱';
        $evaluate[0]['content'] = '咨询师很暖心很有耐心，帮我拆解了困扰我很久的问题，让我及时走出了，消耗了我的情绪';
        $evaluate[0]['img'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIZMiaButw1YZNIicC0Fn0fzgzAvliatlvYdGBnXMN6ZwGcXOpvBDicRHBKiaxnjLwKkBRausWXVW0xMTw/132';
        $evaluate[1]['name'] = '超_越梦想';
        $evaluate[1]['content'] = '咨询师给了我很多的支持，在没有人理解我的决定时，给了我一定的动力';
        $evaluate[1]['img'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/NGZ5uibCKa5SIkMhLe4RcTv0bbSJHiaSnmw0KP81LmdFjH9Y6Hia8ficzVVy1okwtbvQ6RjVYCeYGZhShMmOIR4bSw/132';
        $data['evaluate'] = $evaluate;
        //服务介绍
        $lxxy = [];
        $lxxy[0]['title'] = 'MBTI人格类型校验';
        $lxxy[0]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $lxxy[1]['title'] = '深层性格解读';
        $lxxy[1]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $lxxy[2]['title'] = '深层性格解读';
        $lxxy[2]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $data['fwjs'] = $lxxy;
        //咨询方式
        $zxfs = [];
        $zxfs[0]['title'] = '电话';
        $zxfs[0]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $zxfs[1]['title'] = '微信';
        $zxfs[1]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $zxfs[2]['title'] = '线下面对面咨询';
        $zxfs[2]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $data['zxfs'] = $zxfs;
        //咨询须知
        $zxxz =[];
        $zxxz[0]['title'] = '回应时长';
        $zxxz[0]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $zxxz[1]['title'] = '变更预约说明';
        $zxxz[1]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $zxxz[2]['title'] = '爽约/迟到说明';
        $zxxz[2]['content'] = '觉得测试结果中的描述和自己不符合？咨询师将与你沟通，并确定你的类型';
        $data['zxxz'] = $zxxz;
        $this->ajaxSuccess($data);
    }
    //预约支付
    public function customer_pay(){

        //
        $tel = $this->request->param('tel');
        $cm_id = $this->request->param('cm_id');

        if (!preg_match("/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/", $tel)) {
           $this->ajaxError('请输入正确的手机号');
        }
        if(!is_numeric($cm_id)){
            $this->ajaxError('请选择咨询时间');
        }

        $order_no = doOrderSn('YX');

        $cm = Db::name('customer_money')->where('cm_id',$cm_id)->find();

        $ins = [];
        $ins['uid'] = $this->uid;
        $ins['tel'] = $tel;
        $ins['spec'] = $cm_id;
        $ins['money'] = $cm['original_price'];
        $ins['price'] = $cm['price'];
        $ins['order_no'] = $order_no;
        $ins['create_time'] = time();
        $ins['minute'] = $cm['minute'];
        $ins['state'] = 0;

        $r = Db::name('customer_list')->insert($ins);

        $openid = Db::name('users')->where('u_id',$this->uid)->value('openid');
        $wxpay = new wechatpay(1);
        $order = array(
            'body'         => 'mbit购买',
            'detail'       => 'mbit购买',
//            'total_fee'    => $cm['price'] * 100, //分
            'total_fee'    => '0.01' * 100, //分
            'out_trade_no' => $order_no,
            'trade_type'=>'JSAPI',
            'notify_url'       => 'https://xlcp.redyin.net/home/index/about_notify',
        );
        $res = $wxpay ->jspay($order,$openid);
        $data = json_decode($res);
        $this->ajaxSuccess($data);
    }
    //详细
    public function details()
    {
        $data = [];
        $list[0]['title'] = '性格简要解读';
        $list[0]['content'] = '容忍、不拘泥；是冷静的观察者，但面临问题能迅速行动，找出可行的解决方法。能够分析哪些东西可以使事情进行顺利，找出实际问题的症结。很重视事情的前因后果，能够以理性的原则把事情组织起来，重视效率。';
        $list[1]['title'] = '基本解读';
        $list[1]['content'] = '容忍、不拘泥；是冷静的观察者，但面临问题能迅速行动，找出可行的解决方法。能够分析哪些东西可以使事情进行顺利，找出实际问题的症结。很重视事情的前因后果，能够以理性的原则把事情组织起来，重视效率。';
        $data['list'] = $list;
        $data['outcome'] = 'ESPO';
        $data['type'] = '冒险家，痞子绅士气质';
        $data['time'] = '2021-6-9';

        $this->ajaxSuccess($data);
    }




















































}

